package com.ruoyi.recycle.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Component
public class OrderNoGenerateUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static Long getLeftMillis() {
        Long end = LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        Long cur = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        return end - cur;
    }

    public String getIncr(String shopId) {

        LocalDateTime now = LocalDateTime.now();
        String dateTime = DateTimeFormatter.ofPattern("yyMMdd").format(now);
        //key规则：yyMMdd+shopId，有效期24小时
        StringBuffer key = new StringBuffer(shopId).append(dateTime);
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key.toString(), redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        if (increment == 0) {
            Long end = LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Long cur = now.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            increment = entityIdCounter.getAndIncrement();
            entityIdCounter.expire(end - cur, TimeUnit.MILLISECONDS);
        }
        DecimalFormat df = new DecimalFormat("00000");
        return key.append(df.format(increment)).toString();
    }
}
